from flask import Flask, request, jsonify, render_template
import uuid
import broadscope_bailian
from flask_cors import CORS
import time

app = Flask(__name__)
CORS(app, supports_credentials=True)  # 启用 CORS

access_key_id = "LTAI5tFFFFy3SmEbFFLrN1oa"
access_key_secret = "ardTMLGBNATMKyU7qPak8QJuO1oMRg"
agent_key = "8ab776745f9c4b1bb11211781041a767_p_efm"

token = None
token_expiration = None


def get_token():
    global token
    global token_expiration
    # 如果 token 已经过期或即将过期，则重新获取一个新的 token
    if not token or time.time() > token_expiration - 600:  # 提前 10 分钟重新获取 token
        client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
                                                      agent_key=agent_key)
        token = client.get_token()
        token_expiration = time.time() + 3600

    return token


@app.route("/", methods=["POST"])
def completions():
    token = get_token()
    broadscope_bailian.api_key = token

    app_id = "4de1f488857a4c30845b57bf6d5b1bdc"

    prompt = request.json.get("prompt")

    session_id = str(uuid.uuid4()).replace("-", "")

    resp = broadscope_bailian.Completions(token=token).call(app_id=app_id, prompt=prompt, session_id=session_id)

    print(resp)

    return jsonify(resp)
    # return resp.Text


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    # app.run(debug=True)
    app.run(debug=True, host='0.0.0.0')
